package cn.regexp.job.executor.jobHandler;


import cn.regexp.domain.ShopCanteen;
import cn.regexp.service.ICanteenService;
import cn.regexp.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class CanteenXxlJob {
    private static Logger logger = LoggerFactory.getLogger(CanteenXxlJob.class);

    @Autowired
    private ICanteenService canteenService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @XxlJob("cacheCanteenJobHandler")
    public void cacheCanteenJobHandler() throws Exception {
        XxlJobHelper.log("同步餐厅、窗口信息到Redis --> start");
        String key = RedisKeys.CANTEEN_INFO.join();
        // 如果存在该 key，则删除
        if (Objects.equals(redisTemplate.hasKey(key),Boolean.TRUE)) {
            redisTemplate.delete(key);
        }
        // 查询所有餐厅信息
        List<ShopCanteen> canteenList = canteenService.queryCanteen();
        logger.info("总共有" + canteenList.size() + "条信息");
        // 将餐厅信息存入 Redis 中
        canteenList.forEach(item -> redisTemplate.opsForHash().put(key, item.getId().toString(),
                JSON.toJSONString(item)));
        // 设置 key 过期时间为7天
        redisTemplate.expire(key, RedisKeys.CANTEEN_INFO.getTime(), TimeUnit.DAYS);
        XxlJobHelper.log("同步餐厅、窗口信息到Redis --> end");
    }
}
